package com.hooda.container;

import com.hooda.servlet.NotFoundServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangzp
 * @version 1.0, 2021/10/18
 */
public class Context {

    private String dir;

    private Wrapper empty = new Wrapper(NotFoundServlet.class.getName());

    private Map<String, Wrapper> wrappers = new HashMap<>();

    public Context(String dir) {
        this.dir = dir;
        init();
    }

    private void init() {
        if (null == dir) {
            return;
        }

        try {
            FileInputStream inputStream = new FileInputStream(dir + "/web.xml");

            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> servletNodes = rootElement.selectNodes("//servlet");
            if (servletNodes == null) {
                return;
            }

            for (Element element : servletNodes) {
                String servletName = element.selectSingleNode("servlet-name").getStringValue();
                String servletClass = element.selectSingleNode("servlet-class").getStringValue();

                Element servletMappingNode = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMappingNode.selectSingleNode("url-pattern").getStringValue();

                wrappers.put(urlPattern, new Wrapper(servletClass));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public String getDir() {
        return dir;
    }

    public Wrapper getWrapper(String urlPattern) {
        if (wrappers.containsKey(urlPattern)) {
            return wrappers.get(urlPattern);
        }
        return empty;
    }
}
